package com.dylovedz.javafxphone.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.dylovedz.javafxphone.controller.vo.WechatExcelVO;
import com.dylovedz.javafxphone.util.ExcelUtil;
import javafx.concurrent.Task;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class MaterialRunTask extends Task<Number> {

    private static final Logger logger = LoggerFactory.getLogger(MaterialRunTask.class);
    private WxMpServiceImpl wxMpService;
    private String outDir;
    private WechatService wechatService;
    private ForkJoinPool forkJoinPool;

    public static AtomicInteger completeNum;

    public MaterialRunTask(WxMpServiceImpl wxMpService, WechatService wechatService, String outDir) {
        this.wxMpService = wxMpService;
        this.wechatService = wechatService;
        this.outDir = outDir;
    }

    public static void addNum() {
        completeNum.getAndIncrement();
    }

    public static Integer getNum() {
        return completeNum.get();
    }

    @Override
    protected Number call() throws Exception {
        completeNum = new AtomicInteger(0);
        forkJoinPool = new ForkJoinPool();
        int allTask = wechatService.getTotalPage(wxMpService, 20);
        MaterialTask materialTask = new MaterialTask(wxMpService, wechatService, 0, allTask, outDir);
        Future<List<WechatExcelVO>> future = forkJoinPool.submit(materialTask);
        //future.cancel(true);
        while(!future.isDone() && !future.isCancelled()){
            if (getNum() > allTask * 20L * 0.8) {
                this.updateProgress(0.8, 1);
            } else {
                this.updateProgress(getNum(), allTask * 20L);
            }

            logger.info("getDonePage:{}", getNum());
            logger.info("getQueuedSubmissionCount:{}", forkJoinPool.getQueuedSubmissionCount());
            logger.info("getQueuedTaskCount:{}", forkJoinPool.getQueuedTaskCount());
            logger.info("getActiveThreadCount:{}", forkJoinPool.getActiveThreadCount());
            logger.info("getPoolSize:{}", forkJoinPool.getPoolSize());
            logger.info("getStealCount:{}", forkJoinPool.getStealCount());
            logger.info("getRunningThreadCount:{}", forkJoinPool.getRunningThreadCount());
            logger.info("getParallelism:{}", forkJoinPool.getParallelism());
            logger.info("getRunningThreadCount:{}", forkJoinPool.isTerminated());
            logger.info("=========================================================================");
            TimeUnit.SECONDS.sleep(1);
        }
        this.updateProgress(0.9, 1);
        List<WechatExcelVO> wechatExcelList = future.get();
        wechatExcelList.sort(Comparator.comparingInt(WechatExcelVO::getOffset));
        this.updateMessage("总发文数为：" + wechatExcelList.size());
        // 关闭
        forkJoinPool.shutdown();
        this.updateProgress(allTask * 0.95, allTask);
        String date = DateUtil.format(DateUtil.date(), "MMddHHmmss");
        File file = FileUtil.file(FileUtil.file(outDir), "article" + date + ".xlsx");
        ExcelUtil.write(file, "文章导出", WechatExcelVO.class, wechatExcelList);
        this.updateProgress(1, 1);
        return 1;
    }

    @Override
    protected void cancelled() {
        super.cancelled();
        if (forkJoinPool != null) {
            forkJoinPool.shutdownNow();
        }
    }
}
